import { Modal, Form, Input, InputNumber, DatePicker, Switch } from 'antd';
import { useEffect } from 'react';
import type { User } from '../api/users';
import dayjs from 'dayjs';

interface UserModalProps {
  visible: boolean;
  user: User | null;
  onOk: (values: any) => void;
  onCancel: () => void;
}

export const UserModal = ({ visible, user, onOk, onCancel }: UserModalProps) => {
  const [form] = Form.useForm();

  useEffect(() => {
    if (user) {
      form.setFieldsValue({
        ...user,
        expire_at: user.expire_at ? dayjs(user.expire_at) : null,
      });
    } else {
      form.resetFields();
    }
  }, [user, form]);

  const handleOk = async () => {
    try {
      const values = await form.validateFields();
      onOk({
        ...values,
        expire_at: values.expire_at ? values.expire_at.toISOString() : null,
      });
    } catch (error) {
      console.error('Validation failed:', error);
    }
  };

  return (
    <Modal
      title={user ? 'Edit User' : 'Add User'}
      open={visible}
      onOk={handleOk}
      onCancel={onCancel}
      width={600}
    >
      <Form form={form} layout="vertical">
        <Form.Item
          name="username"
          label="Username"
          rules={[{ required: true, message: 'Please input username!' }]}
        >
          <Input disabled={!!user} />
        </Form.Item>

        <Form.Item
          name="password"
          label="Password"
          rules={[{ required: !user, message: 'Please input password!' }]}
        >
          <Input.Password placeholder={user ? 'Leave blank to keep current' : ''} />
        </Form.Item>

        <Form.Item name="max_bandwidth_up" label="Upload Bandwidth (Mbps)">
          <InputNumber min={0} style={{ width: '100%' }} placeholder="0 = unlimited" />
        </Form.Item>

        <Form.Item name="max_bandwidth_down" label="Download Bandwidth (Mbps)">
          <InputNumber min={0} style={{ width: '100%' }} placeholder="0 = unlimited" />
        </Form.Item>

        <Form.Item name="traffic_limit" label="Traffic Limit (GB)">
          <InputNumber min={0} style={{ width: '100%' }} placeholder="0 = unlimited" />
        </Form.Item>

        <Form.Item name="expire_at" label="Expiration Date">
          <DatePicker showTime style={{ width: '100%' }} />
        </Form.Item>

        <Form.Item name="enabled" label="Enabled" valuePropName="checked" initialValue={true}>
          <Switch />
        </Form.Item>
      </Form>
    </Modal>
  );
};
